import 'package:flutter/material.dart';
import '../services/ScreenAdatper.dart';
import 'package:dio/dio.dart';
import '../config/config.dart';
import '../model/ProductListModdel.dart';
import '../widget/loaddingWidget.dart';
class ProductListPage extends StatefulWidget {
  Map arguments;
  ProductListPage({Key key,this.arguments}) : super(key: key);
  _ProductListPageState createState() => _ProductListPageState();
}

class _ProductListPageState extends State<ProductListPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  ScrollController _scrollController = new ScrollController();
  int _subHederIndex = 1;
  int _page = 1;
  int _pageSize = 10;
  String _sort = '';
  List _prodicList = [];
  // 数据是否全部加载完毕
  bool hasMore = true;
  // 数据是否加载中
  bool onload  = false; 
   //是否有搜索的数据
  bool _hasData = true;
  
  List _subHederList = [
    {"id":1,'title':'综合','flieds':'all','sort':-1},  // 升序 price_1  price:1
    {"id":2,'title':'销量','flieds':'salecount','sort':-1},
    {"id":3,'title':'价格','flieds':'price','sort':-1},
    {"id":4,'title':'筛选'},
  ];
  //给search 设置默认值
  var _initKeyWordsController = new TextEditingController();
  var _keywords;
  var _cid;
  @override
  void initState() { 
    super.initState();
    this._keywords = widget.arguments['keywords'];
    this._cid = widget.arguments['cid'];
    this._initKeyWordsController.text = this._keywords ?? '';
    _getProdicList();
    _scrollController.addListener((){
       if(_scrollController.position.pixels > _scrollController.position.maxScrollExtent - 40){
          this._getProdicList();
       }
    });
  }
  _getProdicList()async{
    if(this.hasMore && !this.onload){
      setState(() {
        // 防止数据多次请求
        this.onload = true;
      });
      var api = "${Config.domain}api/plist?${this._keywords != null ? 'search=${this._keywords}' : 'cid=${this._cid}'}&page=${this._page}&sort=${this._sort}&pageSize=${this._pageSize}";
      print(api);
      var reslut = await new Dio().get(api);
      var productList = new ProductListModdel.fromJson(reslut.data); 

      //判断是否有搜索数据
      if(productList.result.length == 0 && this._page == 1){
        setState(() {
          this._hasData=false; 
        });
      }else{
        this._hasData=true; 
      }
      setState(() {
        this._prodicList.addAll(productList.result);
        this._page++;
        this.onload = false;
        if(productList.result.length < this._pageSize){
          this.hasMore = false;
        }
      }); 
    }
    
  }
  _prodiclistItem(item){
    String sPic = item.pic;
    sPic = Config.domain + sPic.replaceAll('\\', '/');
    return InkWell(
      child: Row(
        children: <Widget>[
          Container(
            width: ScreenAdatper.width(180),
            height: ScreenAdatper.height(180),
            child: Image.network("${sPic}",fit:BoxFit.cover),
          ),
          Expanded(
            flex: 1,
            child: Container(
              margin: EdgeInsets.only(right: 10,left: 10),
              height: ScreenAdatper.height(180),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Text(item.title,maxLines: 2,overflow:TextOverflow.ellipsis ,),
                  Row(
                    children: <Widget>[
                      Container(
                        height: ScreenAdatper.height(36),
                        margin: EdgeInsets.only(right: 10),
                        padding: EdgeInsets.fromLTRB(10, 2.5, 10, 0),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          color: Color.fromRGBO(230, 230, 230, 0.9)
                        ),
                        child: Text("标签1",style: TextStyle(fontSize: 12),),
                      ),
                      Container(
                        height: ScreenAdatper.height(36),
                        margin: EdgeInsets.only(right: 10),
                        padding: EdgeInsets.fromLTRB(10, 2.5, 10, 0),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          color: Color.fromRGBO(230, 230, 230, 0.9)
                        ),
                        child: Text("标签2",style: TextStyle(fontSize: 12),),
                      )
                    ],
                  ),
                  Text('${item.price}',
                    style: TextStyle(
                      color: Colors.red,
                      fontSize: 16
                    ),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
      onTap: (){
        print(item.sId);
        Navigator.pushNamed(context, '/productContent',arguments: {
          'id':item.sId
        });
      },
    );
  }
  _prodiclistWidget(){
    if(this._prodicList.length > 0){
        return Container(
        padding: EdgeInsets.all(10),
        margin: EdgeInsets.only(top: ScreenAdatper.height(65)),
        child: ListView.builder(
          controller: _scrollController,
          itemBuilder: (context,index){
            return Column(
              children: <Widget>[
                _prodiclistItem(this._prodicList[index]),
                Divider(),
                index == this._prodicList.length - 1 ? LoaddingWidget(hasMore: this.hasMore,) : Text("")
              ],
            );
          },
          itemCount: this._prodicList.length,
        ),
      );
    }else{
      return LoaddingWidget(hasMore: this.hasMore,);
    }
  }
  _subHederChange(value){
    if(value['id'] == 4){
      this._scaffoldKey.currentState.openEndDrawer();
    }else{
      setState(() {
        if(this._prodicList.length > 0){
          _scrollController.jumpTo(0);
        }
        this._subHederIndex = value['id'];
        this._sort = "${value['flieds']}_${value['sort']}";
        this._subHederList[value['id'] - 1]['sort']= value['sort'] == -1 ? 1 : -1;
        this._page = 1;
        this._prodicList = [];
        this.hasMore = true;
        this.onload  = false;
        this._getProdicList();
      });
    }
  }
 
  Widget _showIcon(value){
    if(value['id'] == 3 || value['id'] == 2 ){
      return Icon(value['sort'] == -1 ?Icons.arrow_drop_down : Icons.arrow_drop_up);
    }
    return Text("");
  }
  _subHederWidget(){
    return Positioned(
        width: ScreenAdatper.width(750),
        height: ScreenAdatper.height(80),
        top: 0,
        child: Container(
          width: ScreenAdatper.width(750),
          height: ScreenAdatper.height(80),
          decoration: BoxDecoration(
            border: Border(
              bottom:BorderSide(
                width: 1,
                color: Color.fromRGBO(233, 233, 233, 0.9)
              )
            )
          ),
          child: Row(
            children:this._subHederList.map((value){
                return Expanded(
                  flex: 1,
                  child: InkWell(
                    child: Padding(
                      padding: EdgeInsets.fromLTRB(0,ScreenAdatper.height(16), 0, ScreenAdatper.height(16)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text("${value['title']}",textAlign: TextAlign.center,style: TextStyle(color:this._subHederIndex == value['id'] ? Colors.red : Colors.black87)),
                          _showIcon(value) 
                        ],
                      ),
                    ),
                    onTap: (){
                      _subHederChange(value);
                    },
                  ),
                );
              }).toList()
          )
        ),
      );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Container(
          height:ScreenAdatper.height(68),
          decoration: BoxDecoration(
            color: Color.fromRGBO(233, 233, 233, 0.8),
            borderRadius: BorderRadius.circular(30)
          ),
          child: Container(
            child: TextField( 
              controller: _initKeyWordsController,
              decoration: InputDecoration(
                hintText: "请输入搜索内容",
                contentPadding: EdgeInsets.only(top: ScreenAdatper.height(48),left: ScreenAdatper.width(30),right: ScreenAdatper.width(30)),
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                  borderRadius: BorderRadius.circular(30)
                )
              ),
              onChanged:(value){      //监听
                setState(() {
                  this._keywords = value;
                });
              },
            )
          ),
        ),
        actions: <Widget>[
          InkWell(
            child: Container(
              alignment: Alignment.center,
              height:ScreenAdatper.height(68),
              width: ScreenAdatper.width(120),
              child: Text("搜索"),
            ),
            onTap: (){ 
               this._subHederChange(this._subHederList[0]);
            },
          )    
        ],
      ),
      endDrawer: Drawer(
        child: Container(
          child: Text("Drawer"),
        ),
      ),
      body: _hasData ? Stack(
        children: <Widget>[
          _prodiclistWidget(),
          _subHederWidget()
        ],
      ):Center(
        child: Text("没有您要浏览的数据")
      ) 
    );
  }
}